<template>
  <view class="container">
    <!-- 地图容器 -->
    <view
      :style="{ height: `${containerHeight}vh` }"
      id="map-container"
      class="map-container"
    ></view>
    <!-- 控制面板 -->
    <!-- <view class="control-panel">
      <button @click="startTracking">{{ isTracking ? '停止' : '开始' }}追踪</button>
   </view> -->
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted, reactive, watch, toRefs } from 'vue'
import { onReady, onShow } from '@dcloudio/uni-app'
import AMapLoader from '@amap/amap-jsapi-loader'
import axios from 'axios'
// 父组件传值
const props = defineProps([
  'maxHeight',
  'currentPosition',
  'carList',
  'createCircle',
  'radius',
  'worthIt',
  'centerPoint',
])
// 地图容器高度（带默认值）
const containerHeight = ref(props.maxHeight || 90)
// 响应式数据
const mapInstance = ref(null)
const carMarker = ref(null)
const isTracking = ref(false)
const trackInterval = ref(null)
const currentPosition = reactive(props.currentPosition || [116.397428, 39.90923]) // 初始坐标
const createCircle = ref(props.createCircle || false) // 围栏事件
// 围栏默认有没有数据
const worthIt = ref(props.worthIt || false)
// 围栏默认有数据传过来的中心点
const centerPoint = reactive(props.centerPoint || [])

const progress = ref(0)
// 地图实例
let map = null
let circle = null

// 地址信息
const address = ref('')
const { radius } = toRefs(props)

let animationTimer = null
onShow(() => {})

const initMap = () => {
  try {
    if (currentPosition.value) {
      console.log(currentPosition.value, 'currentPosition.value')

      // 创建初始车辆标记
      createCarMarker(currentPosition.value)
      getAddress(currentPosition.value[0], currentPosition.value[1])
    }
    if (createCircle.value) {
      if (worthIt.value) {
        createCircle1(centerPoint.value, props.radius)
      }
      mapInstance.value.on('click', (e) => {
        if (circle) mapInstance.value.remove(circle)
        createCircle1(e.lnglat, props.radius)
      })
    }
  } catch (error) {
    console.error('地图加载失败:', error)
  }
}

// 初始化地图
onMounted(async () => {
  // 加载高德地图 SDK
  const AMap = await AMapLoader.load({
    key: '4c09e40f12d0d0d12995a2ff05bd071e', // 替换为你的 Key
    version: '2.0', // SDK 版本
    plugins: ['AMap.Geocoder'], // 加载逆地理编码插件
  })
  // AMap.convertFrom(currentPosition.value, 'gps', (status, result) => {
  //   console.log(result)
  //   if (result.info === 'ok') {
  //     const amapLng = result.locations[0].lng
  //     const amapLat = result.locations[0].lat
  //     console.log('API转换结果:', amapLng, amapLat)
  //   }
  // })
  // // 初始化地图
  mapInstance.value = new AMap.Map('map-container', {
    zoom: 15, // 缩放级别
    center: currentPosition.value,
    viewMode: '3D', // 启用3D视角
  })
  // 先加载插件
  AMap.plugin(['AMap.MoveAnimation'], () => {
    // 插件加载完成后初始化地图
    initMap()
  })

  // 初始化控件
  AMap.plugin(['AMap.Scale', 'AMap.ToolBar'], () => {
    mapInstance.value.addControl(new AMap.Scale())
    mapInstance.value.addControl(new AMap.ToolBar())
  })
})

// 定义 emit
const emit = defineEmits(['update-value'])
// 逆地理编码函数
const getAddress = (lng, lat) => {
  axios({
    url: `https://restapi.amap.com/v3/geocode/regeo?location=${lng},${lat}&key=c59b7fb2d10278cf28df033869f15277&radius=1000&extensions=all`,
    method: 'get',
  }).then((res) => {
    if (res.data.status == '1') {
      address.value = res.data.regeocode.formatted_address
      emit('update-value', address.value)
      console.log(address.value)
    } else {
      // this.$message({ message: res.info, type: 'error' })
    }
  })
}

// 创建车辆标记
const createCarMarker = (position, angle = 0) => {
  console.log(position, 'position')

  if (carMarker.value) {
    mapInstance.value.remove(carMarker.value)
  }
  carMarker.value = new AMap.Marker({
    position: position,
    content: `
      <div style="position:relative">
        <img src="/static/car.png"
             style="width:40px;height:40px;transform:rotate(${angle}deg)">
      </div>
    `,
    offset: new AMap.Pixel(-20, -20), // 调整定位点
  })
  mapInstance.value.add(carMarker.value)
}

// 计算方向角度（基于两点）
const calculateAngle = (oldPos, newPos) => {
  const dx = newPos[0] - oldPos[0]
  const dy = newPos[1] - oldPos[1]
  return (Math.atan2(dy, dx) * 180) / Math.PI
}

// 模拟位置更新（实际应对接API）
const updatePosition = () => {
  const oldPos = [...currentPosition]

  // 生成新坐标（模拟移动）
  currentPosition = [
    oldPos[0] + (Math.random() - 0.5) * 0.001,
    oldPos[1] + (Math.random() - 0.5) * 0.001,
  ]

  // 计算方向
  const angle = calculateAngle(oldPos, currentPosition)

  // 更新标记
  carMarker.value.setPosition(currentPosition)
  carMarker.value.setContent(`
    <div style="position:relative">
      <img src="/static/car.png"
           style="width:40px;height:40px;transform:rotate(${angle}deg)">
      <div style="position:absolute;top:-8px;left:17px;width:6px;height:6px;
                  background:red;border-radius:50%"></div>
    </div>
  `)

  // 自动定位
  mapInstance.value.setCenter(currentPosition)
}

// 控制追踪
const startTracking = () => {
  isTracking.value = !isTracking.value
  if (isTracking.value) {
    trackInterval.value = setInterval(updatePosition, 1000)
  } else {
    clearInterval(trackInterval.value)
  }
}

// 生命周期
// onMounted(async () => {
//   // 可选：延迟加载（等父组件传值）
//   // const success = await loadAmap()
//   // if (!success) {
//   //   uni.showToast({ title: '地图加载失败', icon: 'none' })
//   // }
// })

onUnmounted(() => {
  clearInterval(trackInterval.value)
  if (mapInstance.value) {
    mapInstance.value.destroy()
  }
})

// 车辆追踪
// 轨迹线
let trackPolyline = null

// 轨迹数据示例
const trackData = ref([
  // { lng: 116.397428, lat: 39.90923, time: '09:00' },
  // { lng: 116.407428, lat: 39.91923, time: '09:05' },
  // { lng: 116.417428, lat: 39.92923, time: '09:10' },
])

// 初始化地图
const carzz = () => {
  // 创建初始车辆标记
  mapInstance.value.setCenter([trackData.value[0].lng, trackData.value[0].lat])
  createCarMarker([trackData.value[0].lng, trackData.value[0].lat])

  // 绘制轨迹线
  trackPolyline = new AMap.Polyline({
    path: trackData.value.map((p) => [p.lng, p.lat]),
    strokeColor: '#3366FF',
    strokeWeight: 5,
  })
  mapInstance.value.add(trackPolyline)
}

// 播放/暂停控制
const togglePlay = () => {
  console.log(trackData.value, 'trackData.value')
  console.log(props.carList)

  trackData.value = props.carList.value.map((item) => ({
    lng: item.longitude,
    lat: item.latitude,
  }))

  // mapInstance.value.remove(carMarker.value)
  carzz()
  playAnimation()
}
// 播放轨迹动画
const playAnimation = () => {
  if (progress.value >= trackData.value.length - 1) {
    progress.value = 0
  }

  animationTimer = setInterval(() => {
    if (progress.value < trackData.value.length - 1) {
      progress.value++
      updateCarPosition()
    } else {
      clearInterval(animationTimer)
      // isPlaying.value = false
    }
  }, 1000) // 1秒间隔
}
// 更新车辆位置
const updateCarPosition = () => {
  const currentPoint = trackData.value[progress.value]
  console.log(currentPoint, 'currentPoint')

  // 平滑移动动画
  carMarker.value.moveTo([currentPoint.lng, currentPoint.lat], {
    duration: 500,
    autoRotation: true, // 自动调整车头方向
  })

  // 地图中心跟随
  mapInstance.value.setCenter([currentPoint.lng, currentPoint.lat])
}
// 围栏
// 创建圆形围栏
const createCircle1 = (center, radius) => {
  let bj = radius * 1000
  let zb = [center.lng, center.lat]
  console.log(zb)
  console.log(bj)

  // if (circle) mapInstance.value.remove(circle)
  circle = new AMap.Circle({
    center: zb,
    radius: bj,
    // strokeColor: '#FF33FF',
    strokeOpacity: 1,
    strokeWeight: 2,
    fillColor: '#1791fc',
    fillOpacity: 0.4,
  })
  mapInstance.value.add(circle)
  mapInstance.value.setFitView([circle])
  getAddress(center.lng, center.lat)
  mapInstance.value.on('click', (e) => {
    if (circle) mapInstance.value.remove(circle)
    createCircle1(e.lnglat, props.radius)
  })
  let weilan = {
    lng: center.lng,
    lat: center.lat,
    radius: radius,
  }
  emit('weilan', weilan)
}
// 3. 监听值的变化
watch(
  radius, // 监听的响应式变量
  (newVal, oldVal) => {
    console.log('值发生变化:', `旧值: ${oldVal} → 新值: ${newVal}`)

    if (circle) mapInstance.value.remove(circle)
  },
  { immediate: true }, // 可选：立即触发一次
)
// expose ['address']
// 将方法暴露给父组件
defineExpose({
  togglePlay,
})
</script>

<style scoped>
.container {
  height: 100%;
}
.map-container {
  width: 100vw;
  /* height: calc(100vh - 60px); */
  /* height: 100vh; */
}

.control-panel {
  padding: 10px;
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 999;
}

button {
  padding: 8px 20px;
  background-color: #1890ff;
  color: white;
  border-radius: 20px;
  font-size: 14px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
</style>
